package cn.jsprun.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.jsprun.domain.Settings;

public final class ForumCommonsUtil {
	@SuppressWarnings("unchecked")
	public static Map<String, String> queryForumSetInfo(){	
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction ts = session.beginTransaction();
		Map<String, String> forumSetInfoMap = new HashMap<String, String>();
		List<Settings> settings = session.createQuery("from Settings").list();
		ts.commit();
		if(settings!=null)
		{
			for(Settings setting:settings)
			{
				forumSetInfoMap.put(setting.getVariable(), setting.getValue());
			}
		}
		String[] temp = {"forumfounders","bbname","regname","reglinkname","dateformat","userdateformat"};
		for(int i = 0;i<temp.length;i++){
			String value = forumSetInfoMap.get(temp[i]);
			StringBuffer buffer = new StringBuffer();
			if(value!=null)
			{
				int length=value.length();
				for(int j = 0;j<length;j++){
					char charTemp = value.charAt(j);
					if(charTemp=='&'){
						if(j+4<value.length()&&value.substring(j, j+5).equals("&amp;")){
							buffer.append("&amp;");
							j +=4;
						}else{
							buffer.append("&amp;");
						}
					}else{
						buffer.append(charTemp);
					}
				}
			}
			forumSetInfoMap.put(temp[i],buffer.toString());
			buffer=null;
		}
		return forumSetInfoMap;
	}	
	
	public static Integer dateStrToDateLong(String dateStr) throws ParseException{
		if("0".equals(dateStr)){
			return 0;
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		int l = (int)(df.parse(dateStr).getTime()/1000);
		if(l>2147483647){
			l = 2147483647;
		}
		return l;
	}
	public static String dateIntToDate(String dataint){
		SimpleDateFormat df = new SimpleDateFormat("yy-MM-dd HH:mm");
		String timeStr = dataint + "000";
		Long timeLong = Long.parseLong(timeStr);
		String date = df.format(new Date(timeLong));
		return date;
	}
	
	public static String dateIntToDateStr(String dataint){
		SimpleDateFormat df = new SimpleDateFormat("yy-MM-dd");
		String timeStr = dataint + "000";
		Long timeLong = Long.parseLong(timeStr);
		String date = df.format(new Date(timeLong));
		return date;
	}
	public static String DateFormat(String dateline,String type){
		SimpleDateFormat df = new SimpleDateFormat(type);
		String timeStr = dateline + "000";
		Long timeLong = Long.parseLong(timeStr);
		String date = df.format(new Date(timeLong));
		return date;
	}
	
	public static String getStringByLen(String str,int len){
		if(str.length()>len){
			str = str.substring(0,len);
		}
		return str;
	}
}







